﻿#include"../include/SimuZaRan.h"
#include"grid/include/ZaRanGridGenerator.h"
#ifdef Release
//#include "matplotlibcpp.h"
#endif // DEBUG
#include"ReferenceValue/include/RefValue.h"
#include<iostream>
#include<fstream>
SimulationZaRan::SimulationZaRan()
{
	//	fluid_ = new PerfectGas;
	contrl_ = new ContrlPara;
	mesh_ = new MultiGrid;
	//	solver_ = new ZaRanSolver;
	contrl_ = new ContrlPara;
	modelContrl_ = new ModCtrl;
	model_ = new Mod;

}

SimulationZaRan::~SimulationZaRan()
{
	//if (fluid_ != nullptr)
	//	delete fluid_;
	if (contrl_ != nullptr)
		delete contrl_;
	if (mesh_ != nullptr)
		delete mesh_;
	//if (solver_ != nullptr)
	//	delete solver_;
}

void SimulationZaRan::Run()
{
	using std::cout;
	using std::endl;
	contrl_->SetDataGromFile();
	modelContrl_->SetFileName(contrl_->GetGeometryFileName());
	modelContrl_->Input();
	model_->AddMod(modelContrl_->Model());
	model_->GetPointCloud(modelContrl_->Delta());
	ZaranGrid grid;
	ZaRanGridGenerator generator;
	generator.GenZaran2DGridFromModel(grid, *model_, *contrl_);
	ZaRanSolver solver(&grid, *contrl_);
	solver.InitFlow();
	int step = 0;
	std::ofstream fout;
	fout.open("data/step=" + std::to_string(step) + ".dat");
	solver.Output(fout);
	fout.close();
	vector<int>step_vec;
	vector<double>maxResVec, aveResVec;
	while (solver.GetCurrentTime() < solver.GetEndTime())
	{
		solver.Solve();
//#ifdef Release
//		if (step % contrl_->GetCalcResidualStep() == 0)
//		{
//			solver.CalcResidual();
//			step_vec.emplace_back(step);
//			maxResVec.emplace_back(solver.GetMaxResidual());
//			aveResVec.emplace_back(solver.GetAveResidual());
//			//std::cout << aveResVec.back() << std::endl;
//			namespace plt = matplotlibcpp;
//			plt::clf();
//			plt::plot(step_vec, maxResVec);
//			plt::named_plot("Max Residual", step_vec, maxResVec);
//			plt::plot(step_vec, aveResVec);
//			plt::named_plot("Ave Residual", step_vec, aveResVec);
//			// Set x-axis to interval [0,1000000]
//			plt::xlim(10, step_vec.back());
//			// Add graph title
//			plt::title("Residual Plot");
//			// Enable legend.
//			plt::legend();
//			// Display plot continuously
//			plt::pause(0.001);
//		}
//#endif // DEBUG

		if (step % contrl_->GetOutputFlowfieldStep() == 0)
		{
			solver.CalcResidual();

			std::cout << "step = " << step << " dt = " << solver.GetDeltaT() << " max_res=  " << solver.GetMaxResidual() << " grid: " << solver.GetMaxResidualGridIndex() << " node: " << solver.GetMaxResidualNodeIndex() << std::endl;
			std::ofstream fout("data/step=" + std::to_string(step) + ".dat");
			solver.Output(fout);
			fout.close();
		}
		step++;
	}

}
